# -*- coding: UTF-8 -*-
# @Date ：2024/6/27 18:05
# @File：http_push_service
# @Author：mmmme
# @IDE：PyCharm
import hashlib
import json
import time
from collections import OrderedDict
from datetime import datetime

import requests
from typing import List

from src.config.log_config import getLogger
from src.db.sessions import *
from src.service.tjkj_get_http_data import TjkjGetHttpData

logger = getLogger(__name__)


class JyHttpPushService(object):
    def __init__(self, appId: str = None, appSecret: str = None, company_name: str = None,
                 company_code: str = None, TJKJ: TjkjGetHttpData = None):
        self._appId = appId
        self._appSecret = appSecret
        self.headers = {
            "Content-Type": "application/json",
            "appId": self._appId,
            "appSecret": self._appSecret,
            "timestamp": "",
            "sign": ""}
        self.base_url = "http://111.16.49.234:6600/park_data_api"
        self.company_name = company_name
        self.company_code = company_code
        self.TJKJ = TJKJ
        self.db = SqliteSqlalchemy()

    def get_risk_analysis_unit(self):
        """
        安全风险分析单元
        :return:
        """
        url = f"{self.base_url}/security_risk_analysis_unit/report"
        risk_unit = self.TJKJ.get_risk_analysis_unit()
        # logger.info(risk_unit)
        if risk_unit:
            report_data = []
            for data in risk_unit:
                temp_data = {}
                temp_data["id"] = data.get("uuid")
                temp_data["companyCode"] = data.get("companyCode")
                temp_data["hazardCode"] = data.get("hazardCode")
                temp_data["riskUnitName"] = data.get("riskUnitName")
                temp_data["hazardDep"] = data.get("hazardDep")
                temp_data["hazardLiablePerson"] = data.get("hazardLiablePerson", "无").split(",")[0]
                temp_data["createDate"] = data.get("createDate")
                temp_data["createBy"] = data.get("createBy") if data.get("createBy") else data.get("updateBy")
                temp_data["updateDate"] = data.get("createDate")
                temp_data["updateBy"] = data.get("updateBy")
                temp_data["deleted"] = data.get("deleted")
                report_data.append(temp_data)
            self.push_data(url, report_data, '安全风险分析单元')
        else:
            logger.info(f"push data {self.company_name}-安全风险分析单元-共{len(risk_unit)}条,平台没有上报成功记录")

    def get_risk_event(self):
        """
        安全风险事件
        :return:
        """
        url = f"{self.base_url}/security_risk_event/report"
        risk_event = self.TJKJ.get_risk_event()
        if risk_event:
            report_data = []
            for data in risk_event:
                temp_data = {}
                temp_data["id"] = data.get("uuid")
                temp_data["companyCode"] = data.get("companyCode")
                temp_data["riskUnitId"] = data.get("riskUnitId")
                temp_data["riskEventName"] = data.get("riskEventName")
                temp_data["createDate"] = data.get("createDate")
                temp_data["createBy"] = data.get("createBy") if data.get("createBy") else data.get("updateBy")
                temp_data["updateDate"] = data.get("updateDate")
                temp_data["updateBy"] = data.get("updateBy")
                temp_data["deleted"] = data.get("deleted")
                report_data.append(temp_data)
            self.push_data(url, report_data, '安全风险事件')
        else:
            logger.info(f"push data {self.company_name}-安全风险事件-共{len(risk_event)}条,平台没有上报成功记录")

    def get_risk_control_measures(self):
        """
        安全风险管控措施
        :return:
        """
        url = f"{self.base_url}/security_risk_control_measures/report"
        control_measures = self.TJKJ.get_risk_control_measures()
        if control_measures:
            report_data = []
            for data in control_measures:
                temp_data = {}
                temp_data["id"] = data.get("uuid")
                temp_data["companyCode"] = data.get("companyCode")
                temp_data["riskEventId"] = data.get("riskEventId")
                temp_data["dataSrc"] = data.get("dataSrc")
                temp_data["riskMeasureDesc"] = data.get("riskMeasureDesc")
                temp_data["classify1"] = data.get("classify1")
                temp_data["classify2"] = data.get("classify2")
                temp_data["classify3"] = "/"
                temp_data["troubleshootContent"] = data.get("troubleshootContent")
                temp_data["createDate"] = data.get("createDate") if data.get("createDate") else data.get(
                    "updateDate")
                temp_data["createBy"] = data.get("createBy") if data.get("createBy") else data.get("updateBy")
                temp_data["updateDate"] = data.get("updateDate")
                temp_data["updateBy"] = data.get("updateBy")
                temp_data["deleted"] = data.get("deleted")
                report_data.append(temp_data)
            self.push_data(url, report_data, '安全风险管控措施')
        else:
            logger.info(
                f"push data {self.company_name}-安全风险管控措施-共{len(control_measures)}条,平台没有上报成功记录")

    def get_hazard_detection_task(self):
        """
        隐患排查任务
        :return:
        """
        url = f"{self.base_url}/hazard_detection_task/report"
        hazard_detection_task = self.TJKJ.get_hazard_detection_task()
        if hazard_detection_task:
            report_data = []
            for data in hazard_detection_task:
                temp_data = {}
                temp_data["id"] = data.get("uuid")
                temp_data["companyCode"] = data.get("companyCode")
                temp_data["riskMeasureId"] = data.get("riskMeasureId")
                temp_data["troubleshootContent"] = data.get("troubleshootContent") if data.get(
                    "troubleshootContent") else "/"
                temp_data["checkCycle"] = data.get("checkCycle")
                temp_data["checkCycleUnit"] = data.get("checkCycleUnit")
                # temp_data["workStartTime"] = data.get("workStartTime")
                # temp_data["workEndTime"] = data.get("workEndTime")
                # temp_data["workDayType"] = data.get("workDayType")
                temp_data["workType"] = "0"
                # temp_data["taskNum"] = data.get("taskNum")
                temp_data["taskStartTime"] = data.get("createDate")
                temp_data["createDate"] = data.get("createDate")
                temp_data["createBy"] = data.get("createBy")
                temp_data["updateDate"] = data.get("updateDate")
                temp_data["updateBy"] = data.get("updateBy")
                temp_data["deleted"] = data.get("deleted")
                report_data.append(temp_data)
            self.push_data(url, report_data, '隐患排查任务')
        else:
            logger.info(
                f"push data {self.company_name}-隐患排查任务-共{len(hazard_detection_task)}条,平台没有上报成功记录")

    def get_hazard_detection_record(self):
        """
        隐患排查记录
        :return:
        """
        url = f"{self.base_url}/hazard_detection_record/report"
        hazard_detection_record = self.TJKJ.get_hazard_detection_record()
        if hazard_detection_record:
            report_data = []
            for data in hazard_detection_record:
                temp_data = {}
                temp_data["id"] = data.get("uuid").split(",")[0] if data.get("uuid") else data.get("id")
                temp_data["companyCode"] = data.get("companyCode")
                temp_data["checkTaskId"] = data.get("checkTaskId")
                temp_data["checkTime"] = data.get("checkTime")
                temp_data["mobileMe"] = data.get("mobileMe") if data.get("mobileMe") else "/"
                temp_data["isDefend"] = data.get("isDefend") if data.get("isDefend") else "0"
                temp_data["checkStatus"] = data.get("checkStatus")
                temp_data["createByMobile"] = data.get("createByMobile")
                temp_data["createDate"] = data.get("createDate")
                temp_data["createBy"] = data.get("createBy")
                temp_data["updateDate"] = data.get("updateDate")
                temp_data["updateBy"] = data.get("updateBy")
                temp_data["updateByMobile"] = data.get("updateByMobile")
                temp_data["deleted"] = data.get("deleted")
                report_data.append(temp_data)
            self.push_data(url, report_data, '隐患排查记录')
        else:
            logger.info(
                f"push data {self.company_name}-隐患排查记录-共{len(hazard_detection_record)}条,平台没有上报成功记录")

    def get_hazard_detection_information(self):
        """
        隐患排查信息
        :return:
        """
        url = f"{self.base_url}/hazard_detection_information/report"
        hazard_detection_information = self.TJKJ.get_hazard_detection_information()
        if hazard_detection_information:
            report_data = []
            for data in hazard_detection_information:
                temp_data = {}
                temp_data["id"] = data.get("uuid")  #
                temp_data["companyCode"] = data.get("companyCode")  #
                temp_data["hazardCode"] = data.get("hazardCode")  #
                # temp_data["riskMeasureId"] = data.get("riskMeasureId")
                # temp_data["checkRecordId"] = data.get("checkRecordId")
                temp_data["dangerName"] = data.get("dangerName")  #
                temp_data["dangerLevel"] = data.get("dangerLevel")  #
                temp_data["registTime"] = datetime.strptime(data.get("registTime"), "%Y-%m-%d %H:%M:%S").strftime(
                    "%Y-%m-%d")  # 登记时间
                temp_data["registrant"] = data.get("registrant")  #
                temp_data["dangerSrc"] = data.get("dangerSrc", '/')  #
                # temp_data["enforcementId"] = data.get("enforcementId")  # /执法编号
                temp_data["dangerManageType"] = data.get("dangerManageType")  # 治理类型
                temp_data["hazardDangerType"] = data.get("hazardDangerType")  # 隐患类型
                temp_data["hazardCategory"] = data.get("hazardCategory", '0')  # 隐患类别
                temp_data["dangerDesc"] = data.get("dangerDesc", '/')  # 隐患描述
                temp_data["dangerReason"] = data.get("dangerReason", '/')  # /原因分析
                # temp_data["controlMeasures"] = data.get("controlMeasures", '/')  # /控制措施
                temp_data["cost"] = data.get("cost", '/')  # /资金
                temp_data["liablePerson"] = data.get("liablePerson") if data.get("liablePerson") else '/'  # 整改责任人
                temp_data["dangerManageDeadline"] = datetime.strptime(data.get("dangerManageDeadline"),
                                                                      "%Y-%m-%d %H:%M:%S").strftime(
                    "%Y-%m-%d")  # 隐患治理期限
                temp_data["checkAcceptPerson"] = data.get("checkAcceptPerson", '/')  # 验收人姓名
                temp_data["checkAcceptTime"] = datetime.strptime(data.get("checkAcceptTime"),
                                                                 "%Y-%m-%d %H:%M:%S").strftime(
                    "%Y-%m-%d") if data.get("checkAcceptTime") else '/'  # 验收时间
                temp_data["checkAcceptComment"] = data.get("checkAcceptComment", '/')  # /验收情况
                temp_data["dangerState"] = data.get("dangerState")  # 隐患状态
                temp_data["createDate"] = data.get("createDate")
                temp_data["createBy"] = data.get("createBy")
                temp_data["updateDate"] = data.get("updateDate")
                temp_data["updateBy"] = data.get("updateBy")
                temp_data["deleted"] = data.get("deleted")
                report_data.append(temp_data)
            self.push_data(url, report_data, '隐患排查信息')
        else:
            logger.info(
                f"push data {self.company_name}-隐患排查信息-共{len(hazard_detection_information)}条,平台没有上报成功记录")

    def get_job_ticket_information(self):
        """
        特殊作业票证信息
        :return:
        """
        url = f"{self.base_url}/special_job_ticket_information/report"
        job_ticket_information = self.TJKJ.get_job_ticket_information()
        if job_ticket_information:
            report_data = []
            for data in job_ticket_information:
                if data["status"] == 1:
                    try:
                        messages = json.loads(data.get("data")) if data.get("data") else {}
                        if messages:
                            for message in messages.get("data"):
                                temp_data = {}
                                temp_data["id"] = message.get("id")
                                temp_data["companyCode"] = self.company_code  # ;
                                temp_data["ticketType"] = message.get("ticket_type")  # 作业类型1
                                temp_data["issueTime"] = f'{message.get("start_time")}:00'  # 签发时间1
                                temp_data["startTime"] = f'{message.get("start_time")}:00'  # 作业开始时间1
                                temp_data["endTime"] = f'{message.get("end_time")}:00'  # 作业结束时间
                                temp_data["ticketPosition"] = message.get("ticket_position")  # 作业地点1
                                temp_data["ticketContent"] = message.get("ticket_content")  # 作业内容
                                # temp_data["checkedTime"] = message  # 验收时间
                                temp_data["longitude"] = message.get("lng")  # 经度1
                                temp_data["latitude"] = message.get("lat")  # 纬度1
                                temp_data["ticketStatus"] = message.get("ticket_status")  # 作业状态1
                                temp_data["supervisorName"] = message.get("supervisor_name")  # 安全监管人员姓名1
                                temp_data["workerName"] = message.get("worker_name")  # 施工人员姓名1
                                temp_data["workDepartment"] = message.get("workDept_name")  # 施工单位名称1
                                temp_data["isContractorWork"] = message.get("is_contractor_task")  # 是否承包商作业1
                                temp_data["ticketResponsName"] = message.get("major_person")  # 作业负责人1
                                temp_data["majorPersonMobile"] = message.get("major_person_mobile")  # 负责人联系方式
                                temp_data["isChanged"] = message.get("is_changed")  # 作业是否变更过1
                                temp_data["changedCause"] = message.get("changed_reason")  # 作业变更原因
                                temp_data["isCancelled"] = message.get("is_cancelled")  # 作业是否取消
                                temp_data["cancelledCause"] = message.get("cancelled_reason")  # 作业作废原因
                                temp_data["createDate"] = f"{message.get('start_time')}:00"  # ;
                                temp_data["createBy"] = message.get("supervisor_name")  # ;
                                temp_data["updateDate"] = f"{message.get('start_time')}:00"  # ;
                                temp_data["updateBy"] = message.get("supervisor_name")  # ;
                                temp_data["deleted"] = "0"
                                report_data.append(temp_data)
                    except Exception as e:
                        logger.error(f"Exception:{e.args}")
            self.push_data(url, report_data, '特殊作业票证信息')
        else:
            logger.info(
                f"push data {self.company_name}-特殊作业票证信息-共{len(job_ticket_information)}条,平台没有上报成功记录")

    def get_gas_leak_analysis_alarm(self):
        """
        气体泄漏分析报警
        :return:
        """
        url = f"{self.base_url}/gas_leak_analysis_alarm/report"
        pass

    def get_person_real_time_location(self):
        """
        人员实时定位
        :return:
        """
        url = f"{self.base_url}/person_real_time_location/report"
        locations = self.TJKJ.get_person_real_time_location()
        logger.debug(f"locations: {locations}")
        if locations:
            report_data = []
            for location in locations:
                if location["delFlag"] == '0':
                    temp_data = {}
                    temp_data["id"] = location.get("id")
                    temp_data["locaterCode"] = location.get("deviceId")  # 定位终端编码	LOCATER_COD E
                    temp_data["staffCode"] = location.get("deviceId")  # todo 人员编码
                    temp_data["address"] = location.get("")  # /位置描述	ADDRESS
                    temp_data["longitude"] = location.get("longitude")  # 经度	LONGITUDE
                    temp_data["latitude"] = location.get("latitude")  # 纬度	LATITUDE
                    temp_data["createDate"] = location.get("createTime")
                    temp_data["createBy"] = location.get("createBy") if location.get("createBy") else "/"
                    temp_data["updateDate"] = location.get("updateTime")
                    temp_data["updateBy"] = location.get("updateBy") if location.get("updateBy") else "/"
                    temp_data["deleted"] = location.get("delFlag")
                    report_data.append(temp_data)
            self.push_data(url, report_data, '人员实时定位')
        else:
            logger.info(f"push data {self.company_name}-人员实时定位-共{len(locations)}条,平台没有上报成功记录")

    def push_data(self, url: str = None, body: List[dict] = None, content: str = None):
        """
        推送数据
        :param url:
        :param body:
        :param content:
        :return:
        """
        timestamp = str(int(time.time() * 1000))
        self.headers["sign"] = self.create_sign(timestamp)
        self.headers["timestamp"] = timestamp
        # 同一批次的数据id不能重复,去重
        unique_data = [d for n, d in enumerate(body) if d['id'] not in {x['id'] for x in body[:n]}]
        save_list = [{"id": item.get("id"), "companyName": self.company_name,
                      "companyCode": self.company_code, "data": json.dumps(item, ensure_ascii=False)} for
                     item in unique_data]
        if content == "安全风险分析单元":
            self.db.save_risk_analysis_unit(self.db.session, save_list)
        elif content == "安全风险事件":
            self.db.save_risk_event(self.db.session, save_list)
        elif content == "安全风险管控措施":
            self.db.save_risk_control_measures(self.db.session, save_list)
        elif content == "隐患排查任务":
            self.db.save_hazard_detection_task(self.db.session, save_list)
        elif content == "隐患排查记录":
            self.db.save_hazard_detection_record(self.db.session, save_list)
        elif content == "隐患排查信息":
            self.db.save_hazard_detection_information(self.db.session, save_list)
        elif content == "特殊作业票证信息":
            self.db.save_job_ticket_information(self.db.session, save_list)
        elif content == "人员实时定位":
            self.db.save_person_real_time_location(self.db.session, save_list)
        for i in range(0, len(unique_data), 999):
            temp = unique_data[i:i + 999]
            response = requests.post(url=url, headers=self.headers, data=json.dumps(temp)).json()
            logger.info(f"push data {self.company_name}-{content}-共{len(temp)}条:{response}")

    def create_sign(self, timestamp: str = str(int(time.time() * 1000))):
        # 生成签名
        params = OrderedDict()
        params['appId'] = self._appId
        params['timestamp'] = timestamp

        query_string = '&'.join(f'{k}={v}' for k, v in params.items() if v and k not in ('sign', 'key'))
        query_string += f"&key={self._appSecret}"
        self.headers["sign"] = self.md5(query_string).upper()
        self.headers["timestamp"] = timestamp
        return self.md5(query_string).upper()

    def md5(self, data):
        try:
            md = hashlib.md5()
            md.update(data.encode('utf-8'))
            return md.hexdigest().upper()
        except Exception as e:
            logger.error(f"md5 error: {e}")
            return None


if __name__ == '__main__':
    p = JyHttpPushService("yitaihuagong", "c9f7876db9b84104af2adec14c9c2161")
    s = p.create_sign(str(int(time.time() * 1000)))
    print(s)
